<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { ElMessage,ElMessageBox,ElLoading   } from 'element-plus';
import { getToken } from "@/utils/auth";
import { getImportProgress } from '@/api/Marketing/coupon.js';
import { downloadFile } from '@/utils/index.js'

const props = defineProps({
  importUrl: {
    type: String,
    default: 'https://jwkj-health.oss-cn-hangzhou.aliyuncs.com/template/%E4%BC%98%E6%83%A0%E5%88%B8%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
  }
});

const emits = defineEmits(["backImportRangeValue"]);
const importFlag = ref(false);
const baseUrl = import.meta.env.VITE_APP_UPLOADURL;
const fileName = ref("");
const files = ref("");
const fileList = ref([]);
const fileShow = ref(true);
const instance = getCurrentInstance();

const upload = ref(null);
const resultFlag = ref(false);
const loading = ref(null);
const importLoading = ref(false);
const failReason = ref([]);
const batchId = ref("");
const requestHeaders = {
    Authorization: `Bearer ${getToken()}`,
    type:0
};
const timer1 = ref(null);
const importResult = ref(null);
const beforeUpload = (file) => {
    fileName.value = file.name;
    files.value = file;

    let typeArr = file.name.split(".");
    let type = typeArr[typeArr.length - 1];
    let isImgType = ["xls", "xlsx"];
    if (isImgType.indexOf(type) === -1) {
        ElMessage.warning('只能上传xls,xlsx格式文件！');
        fileName.value = "";
        fileList.value = [];
        return false
    }    
    fileList.value = [file];
    
};
const handleSuccess = (res) => {
    importLoading.value = false;
    if(res.code == 0){
        batchId.value = res.data.batchId;
        importFlag.value = false;
        fileShow.value = false;
        setTimeout(()=>{
            fileName.value = "";
            fileList.value = [];
            fileShow.value = true;
            instance.proxy.$forceUpdate();
            _getImportProgress();

        },20)
    }else{

        ElMessage.error("导入失败");
    }

};
const handleFileError = (response)=>{
    ElMessage.error('上传失败') 
    importLoading.value = false
}
const submitUpload = () => {

    if(fileList.value.length<=0){
        ElMessage.warning("文件未选择");
        return;
    }
    upload.value.submit();
    importLoading.value = true;

};
const _getImportProgress = async ()=>{
    try{
        let importInfo = await getImportProgress(batchId.value);
        if(loading.value){
            loading.value.close();
        }
        loading.value = ElLoading.service({
            lock: true,
            text: `正在导入${ importInfo.progress * 100 }%`,
            background: 'rgba(255, 255, 255, 0.6)',
        })
        if((Number(importInfo.progress) * 100) >=100){

            loading.value.close();
            importResult.value = {
                ...importInfo,
                success:importInfo.params.success && importInfo.params.success.length>0?importInfo.params.success.map(value=>{
                    return {
                        code:value.productNo,
                        id:value.productId,
                        name:value.productName,
                        failMsg:value.failMsg,
                        productType:value.productType
                    }
                }):[],
                failReason:importInfo.failReason && importInfo.failReason.length>0?importInfo.failReason.map(value=>{
                    return {
                        code:value.productNo,
                        id:value.productId,
                        name:value.productName,
                        failMsg:value.failMsg,
                        productType:value.productType
                    }
                }):[],
            }
            setTimeout(()=>{
                if(importResult.value.failReason && importResult.value.failReason.length<=0){
                    ElMessageBox(
                        {
                            confirmButtonText: '确定',
                            type: 'success',
                            title: '导入结果',
                            showCancelButton: false,
                            message:`本次成功导入${ importResult.value.successNum }条，失败 0 条`,
                        }
                    )
                }else{
                    resultFlag.value = true;
                    handlerSearch(1);
                }
                
                emits("backImportRangeValue",importResult.value.success)
            },50)

        }else{

            setTimeout(()=>{
                _getImportProgress();
            },300)
            
        }
    }catch(e){
        clearInterval(timer1.value);
    }



}
const downFile = (fileUrl)=>{
    downloadFile(fileUrl);
}
const downFailData = ()=>{
    if(importResult.value.params.failureUrl){
        downloadFile(importResult.value.params.failureUrl);
    }else{
        ElMessage.error('下载失败');
    }

}


const tableLoading = ref(false);
const tableData = ref([]);
const totalPage = ref(0)
const page = reactive({
    pageSize: 6,
    layout: "prev, pager, next",
    currentPage: 1,
    total: 0,
})

const handlerSearch = (nowpage)=>{

    page.currentPage = Number(nowpage);
    tableLoading.value = true;
    setTimeout(async ()=>{
        try{
        
            let params = {
                page:nowpage,
                pageSize:page.pageSize,
            }

            let result = await getFailReasonData(params);
            result = JSON.parse(result)
            console.log(result,777);
            tableData.value = result.data;
            totalPage.value = Number(result.totalPage);
            tableLoading.value = false;
        }catch(e){
            tableLoading.value = false;
        }
    },500) 

}
const getFailReasonData = (params) =>{

    return new Promise((resolve,reject)=>{
        let returnData = JSON.parse(JSON.stringify(importResult.value.failReason));

        params.page = params.page-1;
        let atPage = params.page * params.pageSize;
        returnData = returnData.splice(atPage,params.pageSize);

        resolve(JSON.stringify({
            data:returnData,
            totalPage:importResult.value.failReason.length
        }));


    })
};
defineExpose({importFlag})
</script>
<template>
    <div>
        <el-dialog v-model="importFlag" title="导入商品" width="460px">
            <div class="import-file">
                <div class="import-input">
                    <div style="width: 100%;display:flex;justify-conter:flex-start">
                        <el-input style="width:180px;margin-right: 8px;" placeholder="支持上传xls、xlsx文件" v-model="fileName" :disabled="true"></el-input>
                        <el-upload
                        class="upload-demo"
                        ref="upload"
                        :action="baseUrl + `/gateway/jy-marketing/activity/import/product`"
                        :headers="requestHeaders"
                        :data="{activityType:1}"
                        :on-change="beforeUpload"
                        :show-file-list="false"
                        :on-success="handleSuccess"
                        :auto-upload="false"
                        :file-list="fileList"
                        :on-error="handleFileError"
                        accept=".xls,.xlsx"
                        :multiple="false">
                            <el-button  slot="trigger" type="primary" style="width:116px;">选择导入数据</el-button>
                            <el-button style="width:116px" type="primary" @click="downFile(importUrl)" plain>下载导入模板</el-button>
                        </el-upload>
                    </div>
                    <div style="width: 100%;margin-top:8px;color:#666;font-size: 12px;line-height: 12px;">*单次最多导入1万条</div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="importFlag = false">取消</el-button>
                    <el-button type="primary" @click="submitUpload" :loading="importLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="resultFlag" title="导入结果" width="460px">
            <div class="import-file" v-if="resultFlag">
                <div class="info">
                    <span>本次导入成功{{ importResult.successNum }}条，失败 {{ importResult.failReason.length }} 条。</span>
                    <el-button type="primary" style="width: 116px;" plain @click="downFailData">下载失败数据</el-button>
                </div>
                <div style="width: 100%;">
                    <el-table :data="tableData" style="width: 100%" stripe v-loading="tableLoading">
                        <el-table-column prop="code" label="商品编码" width="150" />
                        <el-table-column prop="failMsg" label="失败原因" fixed="right"/>
                    </el-table>
                    <div class="page">
                        <el-pagination
                        :current-page="page.currentPage"
                        :layout="page.layout"
                        :page-size="page.pageSize"
                        :total="totalPage"
                        background
                        @current-change="handlerSearch">
                    </el-pagination>
                    </div>

                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary"  @click="resultFlag = false">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style lang="less" scoped>
:deep(.el-table__inner-wrapper::before){
    background: rgba(0, 0, 0, 0);
}

.page{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  margin-top:8px;
}
.import-file{
    width: 100%;
    padding-bottom: 6px;
    padding-top:14px;

    .import-input{
        width: 100%;

    }
    .info{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        span{
            color: #000000;
            font-weight: bold;
            line-height: 14px;
            font-weight: bold;
        }
    }
}
</style>